package com.doupi.partner.op.controller;

import com.doupi.partner.manager.authenticator.athuc.CaptchaToken;
import com.doupi.partner.util.RedisUtils;
import com.doupi.partner.util.SftpUtils;
import com.doupi.partner.util.constant.UtilConstants;
import com.google.code.kaptcha.Producer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 工具controller ，比如上传文件，验证码等
 * 
 * @author Super Jens Wang
 * @version 1.0 on 2017/4/2 上午2:05.
 */
@Controller
@RequestMapping("util")
public class UtilController {
	private static final Logger LOGGER = LoggerFactory.getLogger(UtilController.class);
	private static final String VALID_ERROR_MSG = "验证码生成错误";

	@Value("#{doupi_partner_util_config.ftp_path}")
	private String ftpPath;

	@Value("#{doupi_partner_util_config.ftp_domain}")
	private String ftpDomain;

	@Value("#{doupi_partner_util_config.temp_fold}")
	private String tempFold;

	private final SftpUtils sftpUtils;

	private final Producer producer;

	private final RedisUtils redisUtils;

	@Autowired
	public UtilController(@Qualifier("sftpUtils") SftpUtils sftpUtils, @Qualifier("defaultKaptcha") Producer producer, @Qualifier("redisUtils") RedisUtils redisUtils) {
		this.sftpUtils = sftpUtils;
		this.producer = producer;
		this.redisUtils = redisUtils;
	}

	/**
	 * 可以上传多个文件
	 *
	 * @param request
	 *            请求
	 * @param typeFold
	 *            上传目录
	 * @return 文件的url数组
	 * 
	 */
	@ResponseBody
	@CrossOrigin(origins = "*")
	@RequestMapping(value = "upload/{typeFold}", method = RequestMethod.POST)
	public List<String> upload(HttpServletRequest request, @PathVariable("typeFold") String typeFold) {
		List<String> urls = new ArrayList<>();
		try {
			MultipartHttpServletRequest httpServletRequest = (MultipartHttpServletRequest) request;
			Map<String, MultipartFile> files = httpServletRequest.getFileMap();
			sftpUtils.connect();
			for (Map.Entry<String, MultipartFile> entity : files.entrySet()) {
				if (entity != null) {
					MultipartFile multipartFile = entity.getValue();
					String generatorFileName = generatorFileName(multipartFile.getOriginalFilename());
					sftpUtils.upload(ftpPath + typeFold, multipartFile.getInputStream(), generatorFileName);
					urls.add(ftpDomain + "/op/" + typeFold + "/" + generatorFileName);
				}
			}
		} catch (Exception e) {
			LOGGER.error("传文件错误", e);
		} finally {
			if (null != sftpUtils) {
				sftpUtils.disconnect();
			}
		}

		return urls;
	}

	@RequestMapping(value = "imageCode", method = RequestMethod.GET)
	public void imageCode(HttpServletRequest httpRequest, HttpServletResponse httpResponse, String cacheKey) throws IOException {
		try {
			Assert.notNull(cacheKey, "参数：cacheKey不能为空");

			// 设置支持绘图
			System.setProperty("java.awt.headless", "true");

			httpResponse.setDateHeader("Expires", 0L);
			httpResponse.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
			httpResponse.addHeader("Cache-Control", "post-check=0, pre-check=0");
			httpResponse.setHeader("Pragma", "no-cache");
			httpResponse.setContentType("image/jpeg");

			String capText = producer.createText();

			// web session中
			WebUtils.setSessionAttribute(httpRequest, UtilConstants.IDENTIFY_CODE_CACHE_KEY_PREFIX, capText);

			// 缓存 保存两分钟
			redisUtils.setex(CaptchaToken.CAPTCHA_CACHE_KEY, capText, 2 * 60);

			BufferedImage bi = producer.createImage(capText);
			ServletOutputStream out = httpResponse.getOutputStream();
			ImageIO.write(bi, "jpg", out);
			try {
				out.flush();
			} finally {
				out.close();
			}
		} catch (Throwable e) {
			throw new RuntimeException(VALID_ERROR_MSG, e);
		}
	}

	/**
	 * 根据原始文件名生成唯一的文件名
	 */
	private String generatorFileName(String originalFileName) {
		int index = originalFileName.lastIndexOf(".");
		String fileName = Base64Utils.encodeToUrlSafeString(UUID.randomUUID().toString().getBytes());
		if (index > 0) {
			fileName += "." + originalFileName.substring(index + 1);
		}
		return fileName;
	}
}
